package com.yinile.zc03.service;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.google.common.base.Predicates;
import com.yinile.zc03.dao.AuthorRepository;
import com.yinile.zc03.dao.BookRepository;
import com.yinile.zc03.dao.MidBookAuthorRepository;
import com.yinile.zc03.domain.Author;
import com.yinile.zc03.domain.Book;
import com.yinile.zc03.domain.MidBookAuthor;
import com.yinile.zc03.spec.AuthorSpecImpl;
import com.yinile.zc03.sys.page.Pagination;
import com.yinile.zc03.sys.result.BaseResult;
import com.yinile.zc03.sys.result.ObjectOkResult;
import com.yinile.zc03.sys.utils.StringUtils;
import com.yinile.zc03.sys.exception.NoRecordException;

@Service
public class AuthorService {
	@Autowired
	AuthorRepository authorRepository;
	@Autowired
	MidBookAuthorRepository midBookAuthorRepository;
	@Autowired
	BookRepository bookRepository;
	
	public ObjectOkResult findByPage(Integer offset, Integer step, String name, String address) {
		if (offset == null) {
			offset = 0;
		}
		if (step == null) {
			step = 2;
		}
		name = StringUtils.trim(name);
		address = StringUtils.trim(address);
		Sort.Order[] orders = new Sort.Order[1];
		orders[0] = new Sort.Order(Sort.Direction.DESC,"id");
		Page<Author> p = authorRepository.findAll(new AuthorSpecImpl(name, address), new PageRequest(offset, step, new Sort(orders)));		
		List<Author> authorList = p.getContent();
		List<String> authorIds = new ArrayList<String>();
		for (Author item : authorList) {
			authorIds.add(item.getId());
		}
		List<MidBookAuthor> midList = this.midBookAuthorRepository.withAuthorIdsQuery(authorIds);
		HashMap<String, List<String>> map = new HashMap<String, List<String>>();
		List<String> bookIds = new ArrayList<String>();
		for (MidBookAuthor item : midList) {
			String otherEndId = item.getId().getBookId();
			String thisEndId = item.getId().getAuthorId();
			if (bookIds.isEmpty() || !bookIds.contains(otherEndId)) {
				bookIds.add(otherEndId);
			}
			if (map.containsKey(thisEndId)) {
				List<String> tmpList = map.get(thisEndId);
				if (tmpList.isEmpty() || !tmpList.contains(otherEndId)) {
					tmpList.add(otherEndId);
				}
			} else {
				List<String> tmpList = new ArrayList<String>();
				tmpList.add(otherEndId);
				map.put(thisEndId, tmpList);
			}
		}
		List<Book> bookList = bookRepository.withIds(bookIds);
		
		for (Author item : authorList) {
			if (!map.isEmpty() && map.containsKey(item.getId())) {
				List<String> list2 = map.get(item.getId());
				for (Book book : bookList) {
					if (list2.contains(book.getId())) {
						item.getBookList().add(book);
					}
				}
			}
		}
		//		int a = 4/0;
		return new ObjectOkResult(new Pagination<Author>(p));
	}
	
	// 必须是org.springframework.transaction.annotation.Transactional
	// 不能是javax包里的 
	@Transactional
	public ObjectOkResult save(Author author) {
		author.setId(UUID.randomUUID().toString());
		this.authorRepository.save(author);
		return new ObjectOkResult(author);
	}

	public ObjectOkResult findById(String id) {
		if (StringUtils.isEmpty(id)) {
			throw new NoRecordException("缺少ID");
		}
		Author author = this.authorRepository.findOne(id);
		if (author == null) {
			throw new NoRecordException("没有这条记录");
		}
		return new ObjectOkResult(author);
	}
	
	// 必须是org.springframework.transaction.annotation.Transactional
	// 不能是javax包里的
	@Transactional
	public ObjectOkResult update(Author author) {
		if (StringUtils.isEmpty(author.getId())) {
			throw new NoRecordException("缺少ID");
		}
		// 从数据库中查找出来的实体
		Author dbAuthor = this.authorRepository.findOne(author.getId());
		if (dbAuthor == null) {
			throw new NoRecordException("没有这条记录");
		}
		dbAuthor.setAddress(author.getAddress());;
		dbAuthor.setName(author.getName());
//		Timestamp t = new Timestamp(System.currentTimeMillis());
		dbAuthor.setBirthday(author.getBirthday());
		dbAuthor.setBalance(author.getBalance());
		return new ObjectOkResult(author);
	}
	
	// 必须是org.springframework.transaction.annotation.Transactional
	// 不能是javax包里的
	@Transactional
	public BaseResult delete(String id) {
		this.authorRepository.delete(id);
		BaseResult br = new BaseResult();
		br.message = "success";
		return br;
	}
}
